package com.xinchao.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xinchao.constant.BusinessConstant;
import com.xinchao.constant.ModuleConstant;
import com.xinchao.constant.PageConstant;
import com.xinchao.constant.RequestConstant;
import com.xinchao.dao.DepartmentMapper;
import com.xinchao.exception.ServiceException;
import com.xinchao.model.Department;
import com.xinchao.model.OperationLog;
import com.xinchao.model.User;
import com.xinchao.model.dto.DepartmentTreeDTO;
import com.xinchao.model.page.PageInfo;
import com.xinchao.model.vo.DepartmentListVO;
import com.xinchao.model.vo.DepartmentSelectListVO;
import com.xinchao.service.DepartmentService;
import com.xinchao.service.OperationLogService;
import com.xinchao.util.HttpUtils;
import com.xinchao.util.TreeUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.rmi.ServerException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 部门Service实现类
 *
 * @author dxy
 * @date 2018/6/21 16:42
 */
@Service(value = "departmentService")
public class DepartmentServiceImpl implements DepartmentService {

	@Autowired
	private DepartmentMapper departmentMapper;
	@Autowired
	private OperationLogService operationLogService;

	/**
	 * 保存部门
	 *
	 * @param department Department
	 * @param cityCodes  城市编码
	 * @param request    HttpServletRequest
	 */
	@Override
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void insertDepartment(Department department, String cityCodes, String cityNames, HttpServletRequest request) throws ServerException {
		User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
		department.setAddTime(System.currentTimeMillis());
		departmentMapper.insertDepartment(department);
		//保存部门省市区关系
		//注释改功
//		if (StringUtils.isNotBlank(cityCodes)) {
//			saveDepartmentArea(department, cityCodes.split(","), cityNames, request);
//		}
		//记录操作日志
		OperationLog operationLog = new OperationLog();
		operationLog.setOperationContent("保存部门，部门名称为: " + department.getDepartmentName());
		operationLog.setOperationStatus(BusinessConstant.OPERATION_LONG_OPERATION_STATUS_SUCCESS);
		operationLog.setOperationTime(System.currentTimeMillis());
		operationLog.setOperationModule(ModuleConstant.MODULE_USER_PERMISSION + "-" + ModuleConstant.MODULE_DEPARTMENT);
		operationLog.setRealname(loginUser.getRealname());
		operationLog.setUserName(loginUser.getUserName());
		operationLog.setOperationIp(HttpUtils.getRemortIP(request));
		operationLogService.saveOperationLog(operationLog);
	}

	/**
	 * 修改部门
	 *
	 * @param department Department
	 * @param cityCodes  城市编码
	 * @param cityNames	 城市名称
	 * @param request    HttpServletRequest
	 */
	@Override
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void updateDepartment(Department department, String cityCodes, String cityNames, HttpServletRequest request) throws ServerException {
		department.setUpdateTime(System.currentTimeMillis());
		departmentMapper.updateDepartment(department);
		//删除部门省市区关系
//		deleteDepartmentAreaByDepartmentId(department.getDepartmentId());
		//保存部门省市区关系
//		if (StringUtils.isNotBlank(cityCodes)) {
//			saveDepartmentArea(department, cityCodes.split(","), cityNames, request);
//		}
		//记录操作日志
		User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
		OperationLog operationLog = new OperationLog();
		operationLog.setOperationContent("修改部门，部门名称为：" + department.getDepartmentName());
		operationLog.setOperationStatus(BusinessConstant.OPERATION_LONG_OPERATION_STATUS_SUCCESS);
		operationLog.setOperationTime(System.currentTimeMillis());
		operationLog.setOperationModule(ModuleConstant.MODULE_USER_PERMISSION + "-" + ModuleConstant.MODULE_DEPARTMENT);
		operationLog.setRealname(loginUser.getRealname());
		operationLog.setUserName(loginUser.getUserName());
		operationLog.setOperationIp(HttpUtils.getRemortIP(request));
		operationLogService.saveOperationLog(operationLog);
	}

	/**
	 * 通过部门ID获取部门
	 *
	 * @param departmentId 部门ID
	 * @return Department
	 */
	@Override
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public Department getDepartmentById(Long departmentId) {
		return departmentMapper.getDepartmentById(departmentId);
	}

	/**
	 * 部门列表
	 *
	 * @param status         状态
	 * @param departmentName 部门名称
	 * @return Page<DepartmentListVO>
	 */
	@Override
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public PageInfo<DepartmentListVO> listDepartment(Integer status, String departmentName, Integer pageNum, Integer pageSize){
		//设置默认值
		if (pageNum == null) {
			pageNum = PageConstant.DEFAULT_PAGE_NUM;
		}
		if (pageSize == null) {
			pageSize = PageConstant.DEFAULT_PAGE_SIZE;
		}
		PageHelper.startPage(pageNum, pageSize);
		Page<DepartmentListVO> page = departmentMapper.listDepartment(status, departmentName);
		//把Page转化为PageInfo
		PageInfo<DepartmentListVO> pageInfo = new PageInfo<>();
		pageInfo.setPageNum(pageNum);
		pageInfo.setPageSize(pageSize);
		pageInfo.setTotal(page.getTotal());
		pageInfo.setList(page.getResult());
		return pageInfo;
	}

	/**
	 * 获取所有启用的部门
	 *
	 * @return List<DepartmentSelectListVO>
	 */
	@Override
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public List<DepartmentSelectListVO> listDepartmentSelect(){
		return departmentMapper.listDepartmentSelect(BusinessConstant.STATUS_ENABLE);
	}

	/**
	 * 获取部门树列表
	 *
	 * @return List<DepartmentTreeDTO>
	 * @throws ServerException
	 */
	@Override
	public List<DepartmentTreeDTO> listDepartmentTree() {
		List<DepartmentTreeDTO> departmentTreeList = departmentMapper.listDepartmentTree(BusinessConstant.STATUS_ENABLE);
		if (CollectionUtils.isNotEmpty(departmentTreeList)) {
			return TreeUtils.getTreeList(departmentTreeList);
		}
		return new ArrayList<>();
	}

	/**
	 * 保存部门省市区关系
	 *
	 * @param department  部门实体类
	 * @param cityCodeArray 市编码字符串数组
	 * @param cityNames  城市名称
	 * @throws ServerException
	 */
	@Override
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void saveDepartmentArea(Department department, String[] cityCodeArray, String cityNames, HttpServletRequest request) throws ServerException {
		if (department == null || department.getDepartmentId() == null || cityCodeArray == null || cityCodeArray.length <= 0) {
			throw new ServerException("输入参数不能为空");
		}
		departmentMapper.insertDepartmentArea(department.getDepartmentId(), cityCodeArray);
		//记录操作日志
		User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
		OperationLog operationLog = new OperationLog();
		operationLog.setOperationContent("保存部门省市区关系,部门名称为:" + department.getDepartmentName() + ";城市为：" + cityNames);
		operationLog.setOperationStatus(BusinessConstant.OPERATION_LONG_OPERATION_STATUS_SUCCESS);
		operationLog.setOperationTime(System.currentTimeMillis());
		operationLog.setOperationModule(ModuleConstant.MODULE_USER_PERMISSION + "-" + ModuleConstant.MODULE_DEPARTMENT);
		operationLog.setRealname(loginUser.getRealname());
		operationLog.setUserName(loginUser.getUserName());
		operationLog.setOperationIp(HttpUtils.getRemortIP(request));
		operationLogService.saveOperationLog(operationLog);
	}

	/**
	 * 通过部门ID删除部门省市区关系
	 *
	 * @param departmentId 部门ID
	 * @throws ServerException
	 */
	@Override
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void deleteDepartmentAreaByDepartmentId(Long departmentId) throws ServerException {
		if (departmentId == null) {
			throw new ServerException("输入参数不能为空");
		}
		departmentMapper.deleteDepartmentAreaByDepartmentId(departmentId);
	}

	/**
	 * 通过部门ID查找部门所有用户
	 * hanqr 2018-08-09
	 * @param departmentId 部门ID
	 * @return
	 */
	@Override
	public List<HashMap<String, String>> getUsersByDepartmentId(Long departmentId) {
		return departmentMapper.getUsersByDepartmentId(departmentId);
	}

	/**
	 * 启用禁用部门
	 * @param departmentId 部门ID
	 * @param status 状态
	 * @param request HttpServletRequest
	 * @throws ServerException
	 */
	@Override
	public void enableDisableDepartment(Long departmentId, Integer status, HttpServletRequest request) throws ServerException {
		if (departmentId == null || status == null || request == null) {
			throw new ServerException("输入参数不能为空");
		}
		Department department = departmentMapper.getDepartmentById(departmentId);
		if (department == null) {
			throw new ServerException("部门数据不存在，请联系管理员");
		}
		departmentMapper.enableDisableDepartment(departmentId, status);
		User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
		//记录操作日志
		OperationLog operationLog = new OperationLog();
		if (BusinessConstant.STATUS_ENABLE == status) {
			operationLog.setOperationContent("修改部门，启用部门" + department.getDepartmentName());
		} else {
			operationLog.setOperationContent("修改部门，禁用部门" + department.getDepartmentName());
		}
		operationLog.setOperationStatus(BusinessConstant.OPERATION_LONG_OPERATION_STATUS_SUCCESS);
		operationLog.setOperationTime(System.currentTimeMillis());
		operationLog.setOperationModule(ModuleConstant.MODULE_USER_PERMISSION + "-" + ModuleConstant.MODULE_DEPARTMENT);
		operationLog.setRealname(loginUser.getRealname());
		operationLog.setUserName(loginUser.getUserName());
		operationLog.setOperationIp(HttpUtils.getRemortIP(request));
		operationLogService.saveOperationLog(operationLog);
	}


	/**
	 * 批量启用禁用部门
	 * @param ids 部门id（多个英文逗号隔开）
	 * @param status 状态
	 * @param loginUser 登录用户
	 * @param ip 登录用户的ip
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public void batchAbleDisable(String ids, Integer status, User loginUser, String ip) throws ServiceException {
		StringBuilder departmentNames = new StringBuilder();
		if(StringUtils.isNotBlank(ids)){
			String[] idArr = ids.split(",");
			if(idArr.length > 0){
				for (String id : idArr) {
					Department department = departmentMapper.getDepartmentById(Long.parseLong(id));
					if(department == null){
						throw new ServiceException("部门不存在，请联系管理员");
					}
					departmentNames.append(",").append(department.getDepartmentName());
					departmentMapper.enableDisableDepartment(Long.parseLong(id), status);
				}
			}
			if(StringUtils.isNotBlank(departmentNames)){
				String content = "";
				if (BusinessConstant.STATUS_ENABLE == status) {
					content = "批量启用部门，启用部门为：" + departmentNames.toString().substring(1);
				} else {
					content = "批量禁用部门，禁用部门为：" + departmentNames.toString().substring(1);
				}
				operationLogService.saveSuccessOperationLog(content,
						(ModuleConstant.MODULE_USER_PERMISSION+ "-" + ModuleConstant.MODULE_DEPARTMENT), loginUser, ip);
			}
		}
	}
}
